<?php
require_once __DIR__ . '/../models/Bookmark.php';

class BookmarkController {
    private $bookmarkModel;

    public function __construct($db) {
        $this->bookmarkModel = new Bookmark($db);
    }

    public function getAll() {
        $bookmarks = $this->bookmarkModel->getAll();
        foreach ($bookmarks as &$bookmark) {
            if (!preg_match("~^(?:f|ht)tps?://~i", $bookmark['url'])) {
                $bookmark['url'] = "http://" . $bookmark['url'];
            }
            if (empty($bookmark['imgurl'])) {
                $bookmark['imgurl'] = $this->getFaviconOrGenerateIcon($bookmark['url'], $bookmark['title']);
                $this->bookmarkModel->updateImgUrl($bookmark['id'], $bookmark['imgurl']);
            }
            if (empty($bookmark['imgurl'])) {
                $bookmark['imgurl'] = '/public/assets/images/default-icon.png';
            }
            // 如果description为空，使用URL作为描述
            if (empty($bookmark['description'])) {
                $bookmark['description'] = $bookmark['url'];
            }
        }
        return $bookmarks;
    }


    public function getAllCategories() {
        return $this->bookmarkModel->getAllCategories();
    }

    public function addBookmark() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $title = $_POST['title'];
            $url = $_POST['url'];
            $category = $_POST['category'];
            $description = $_POST['description'] ?? '';
            

            // 检查是否提供了图片 URL，如果没有，则生成一个
            if (empty($imgurl)) {
                $imgurl = $this->getFaviconOrGenerateIcon($url, $title);
            }

            $this->bookmarkModel->create($title, $url, $category, $imgurl, $description);
        }
    }
    private function getFaviconOrGenerateIcon($url, $title) {
        $faviconUrl = $this->getFavicon($url);
        if ($faviconUrl) {
            return $faviconUrl;
        } else {
            return $this->generateIcon($title);
        }
    }

    private function getFavicon($url) {
        $parsedUrl = parse_url($url);
        $faviconUrl = $parsedUrl['scheme'] . '://' . $parsedUrl['host'] . '/favicon.ico';
        $headers = @get_headers($faviconUrl);
        if ($headers && strpos($headers[0], '200') !== false) {
            return $faviconUrl;
        }
        return false;
    }

    private function generateIcon($title) {
        $firstChar = mb_substr($title, 0, 1, 'UTF-8');
        $iconFileName = md5($title) . '.png';
        $iconDir = $_SERVER['DOCUMENT_ROOT'] . 'assets/images/icon/';
        $iconPath = $iconDir . $iconFileName;
        $urlPath = '/assets/images/icon/' . $iconFileName;

        // 确保目录存在
        if (!file_exists($iconDir)) {
            mkdir($iconDir, 0777, true);
        }

        // 创建图像
        $image = imagecreatetruecolor(100, 100);
        $bgColor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
        $textColor = imagecolorallocate($image, 255, 255, 255);
        imagefill($image, 0, 0, $bgColor);
        
        // 添加文字
        $font = $_SERVER['DOCUMENT_ROOT'] . 'assets/font/ali.ttf'; // 确保字体文件路径正确
        imagettftext($image, 40, 0, 25, 70, $textColor, $font, $firstChar);

        // 保存图像
        imagepng($image, $iconPath);
        imagedestroy($image);

        // 返回相对URL路径供网页使用
        return $urlPath;
    }


    
    public function editBookmark($id) {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $title = $_POST['title'];
            $url = $_POST['url'];
            $category = $_POST['category'];
            $description = $_POST['description'];
            $imgurl = $_POST['imgurl'];
            $this->bookmarkModel->update($id, $title, $url, $category, $description, $imgurl);
            header('Location: index.php?action=admin');
        } else {
            $bookmark = $this->bookmarkModel->getById($id);
            include __DIR__ . '/../views/edit_bookmark.php';
        }
    }

    public function deleteBookmark($id) {
        $this->bookmarkModel->delete($id);
        header('Location: index.php?action=admin');
    }
}